<?php
namespace app\admin\controller;
use app\Base;
use think\facade\Db;
use think\facade\Cookie;
class Index extends Base{
	//private $request;
	
	public function index()
	{		
		
	}
	
    public function test()
    {
		/*
		$arr=array('username'=>$this->request->post('username'),'password'=>$this->request->post('password'),'email'=>'sdfdfsdfsd');
		$status=$this->validate($arr,\app\admin\validate\User::class);
		if($status)
		{
			return $this->kerror($status);
		}
		
        halt($password);
		*/
    }
	
	//---登录
	public function login()
	{		
		
		$post=array('username'=>$this->request->post('username'),'password'=>$this->request->post('password'));
		$msg=$this->validate($post,\app\admin\validate\User::class);
		if($msg)
		{
			return $this->kerror($msg);
		}		
		$password=skey($post['password']);
		
		$admin=Db::name('admin')->where('username',$post['username'])->find();
		if(!$admin['username'])
		{
			return $this->kerror('账号不存在');
		}
		if($admin['password']!=$password)
		{
			return $this->kerror('密码错误');
		}
		
		$role=Db::name('role')->where("roleid",$admin['roleid'])->find();
		$biaoshi=$role['roleid']?$role['biaoshi']:'user';
		$token=admintoken($admin['userid'],$admin['username']);
		$data=array('biaoshi'=>$biaoshi,'username'=>$admin['username'],'token'=>$token);
		$this->setobj($data);
		
		$this->inittoken($admin['userid'],$data);
		return $this->ok();
	}

    private function inittoken($userid,$data)
	{
		$info=array('inputtime'=>time(),'type'=>1,'expire'=>time()+3600*24*7,'token'=>$data['token']);
		Db::name('login_log')->insert($info);
		//cookie('admintoken',md5($info['inputtime'].$data['token']),3600*24*7);//保存cookie
	}
	
	public function loginout()
	{
		cookie('admintoken',null);
		
	}
	
}
